import React, { PureComponent } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { connect } from 'dva';
import MyPageTable from '@/components/MyPageTable';
import {
  Tabs,
  Button,
  Select,
  Table,
  Card,
  message,
  Icon,
  Modal,
  Form,
  Input,
  Popconfirm,
} from 'antd';
const { TabPane } = Tabs;
const { Option } = Select;
import { onTableData } from '@/utils/utils.js';
@connect(({ messageIndex }) => ({
  ...messageIndex,
}))
@Form.create()
class MessageSetting extends PureComponent {
  state = {
    loading: false,
    onChannel: '1', //默认
    newChannel: null,
    pageNumber: 1,
    pageSize: 10,
    total: 10,
    current: 1,
    selectedRowKeys: [],
    addvisibe: false, //控制添加modal的
    title: 'Banner添加', //添加modal的标题
    imgSrc: '', //上传成功后的url
    nameTitle: 'Banner名称',
    tabActiveKey: '1', //tab组件默认激活的
    editVisible: false,
    modalScore: 'add',
    address: 'banner', //编辑modal，目标位置的默认值
    name: null,
    url: null,
    sort: null,
    status: null,
    img: null,
    id: null,
    channelData: [],
    // 增加、编辑相关
    tempBehavior: null,
    tempId: null,
    tempTitle: null,
    tempStatus: 1,
    tempKeywords: [],
    tempUrl: null,
    tempTime: null,
    tempChannel: null,
    tid: null,
  };
  userBehavior = {
    AUTHORIZED_LOGIN: '授权登陆后但是未成功下单',
    LEASE: '点击立即租赁但未成功下单',
    COLLECTION: '收藏成功后未成功下单',
  };
  // List表头
  columns = [
    {
      title: '模版标题',
      dataIndex: 'title',
      width: '10%',
      align: 'center',
    },
    {
      title: '模版id',
      dataIndex: 'userTemplateId',
      align: 'center',
      width: '10%',
    },
    {
      title: '模版关键词',
      dataIndex: 'keywords',
      align: 'left',
      width: '10%',
      render: data => {
        const arr = JSON.parse(data);
        return (
          <div>
            {arr.map((item, index) => {
              return (
                <p key={index} style={{ marginBottom: 0 }}>
                  {item.keyword}:{item.value}
                </p>
              );
            })}
          </div>
        );
      },
    },
    {
      title: '发送时间间隔',
      dataIndex: 'triggerInterval',
      align: 'center',
      width: '10%',
      render: text => <p>{text}分钟</p>,
    },
    {
      title: '跳转页面',
      dataIndex: 'jumpUrl',
      align: 'center',
      width: '10%',
    },
    {
      title: '用户行为',
      dataIndex: 'userBehavior',
      align: 'center',
      width: '10%',
      render: userBehavior => <p>{this.userBehavior[userBehavior]}</p>,
    },
    {
      title: '是否生效',
      dataIndex: 'status',
      align: 'center',
      width: '10%',
      render: (text, record) => {
        return <p>{record.status === 1 ? '生效' : '不生效'}</p>;
      },
    },
    {
      title: '发送渠道',
      dataIndex: 'channelName',
      align: 'center',
      width: '10%',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      align: 'center',
      width: '10%',
    },
    {
      title: '操作',
      align: 'center',
      width: '10%',
      render: (text, record) => {
        return (
          <div>
            <Popconfirm title="你确定删除吗?" onConfirm={() => this.deleteList(record.id)}>
              {/* <Icon type="delete" style={{ cursor: 'pointer' }} /> */}
              <span style={{ cursor: 'pointer', wordBreak: 'keep-all', color: '#5476F0' }}>删除</span>
            </Popconfirm>
            <span
              style={{ cursor: 'pointer', wordBreak: 'keep-all', marginLeft: 15, color: '#5476F0' }}
              onClick={() => this.edit(record)}
            >修改</span>
            {/* <Icon
              style={{ marginLeft: 15, cursor: 'pointer' }}
              onClick={() => this.edit(record)}
              type="edit"
            /> */}
          </div>
        );
      },
    },
  ];

  componentDidMount() {
    this.getList();
    this.getChannel();
  }
  //获取渠道信息
  getChannel = () => {
    this.props.dispatch({
      type: 'order/PlateformChannel',
      payload: {},
      callback: res => {
        this.setState({
          channelData: res.data,
        });
      },
    });
  };
  //获取List的数据
  getList = () => {
    this.setState(
      {
        loading: true,
      },
      () => {
        this.props.dispatch({
          type: 'messageIndex/getList',
          payload: {
            pageNumber: this.state.pageNumber,
            pageSize: this.state.pageSize,
          },
          callback: res => {
            console.log(res);
            if (res.responseType === 'SUCCESS') {
              message.success('获取信息成功');
              this.setState({
                total: res.data.total,
                current: res.data.current,
                loading: false,
              });
            } else {
              message.error(res.msg);
            }
          },
        });
      },
    );
  };
  //删除List
  deleteList = id => {
    this.props.dispatch({
      type: 'messageIndex/deleteList',
      payload: {
        id: id,
      },
      callback: res => {
        if (res.responseType === 'SUCCESS') {
          message.success('删除成功');
          this.getList();
        } else {
          message.error('删除失败' + res.data.msg);
        }
      },
    });
  };
  edit = record => {
    this.setState(
      {
        addvisibe: true,
        modalScore: 'edit',
        tid: record.id,
        tempKeywords: JSON.parse(record.keywords || '[]'),
      },
      () => {
        this.props.form.setFieldsValue({
          tempChannel: record.channelId,
          tempUrl: record.jumpUrl,
          tempKeywords: JSON.parse(record.keywords || '[]'),
          tempTitle: record.title,
          tempStatus: record.status,
          tempTime: record.triggerInterval,
          tempBehavior: record.userBehavior,
          tempId: record.userTemplateId,
        });
      },
    );
  };

  handleFilter = () => {
    this.getList();
  };

  addTempKeyword() {
    const tempKeywords = [...this.state.tempKeywords];
    tempKeywords.push({
      keyword: '',
      value: '',
    });
    //console.log(tempKeywords)
    this.setState({
      tempKeywords,
    });
  }
  deleteTempKeyword(index) {
    const tempKeywords = [...this.state.tempKeywords];
    tempKeywords.splice(index, 1);
    //console.log(tempKeywords)
    this.setState({
      tempKeywords,
    });
  }
  save(e, index, type) {
    const tempKeywords = [...this.state.tempKeywords];
    tempKeywords[index][type] = e.currentTarget.value;
    //console.log(tempKeywords)
    this.setState(
      {
        tempKeywords,
      },
      () => {
        this.props.form.validateFields(['tempKeywords'], { force: true });
      },
    );
  }

  //分页，下一页
  onChange = pageNumber => {
    // alert(pageNumber)
    this.setState(
      {
        pageNumber: pageNumber.current,
      },
      () => {
        this.handleFilter();
      },
    );
  };
  showTotal = () => {
    return `共有${this.state.total}条`;
  };
  //切换每页数量
  onShowSizeChange = pageSize => {
    console.log(pageSize, 'pageSize');
    this.setState(
      {
        pageSize: pageSize.current,
        pageNumber: 1,
      },
      () => {
        this.handleFilter();
      },
    );
  };
  //表格多选框的回调
  onSelectChange = (selectedRowKeys, selectedRows) => {
    this.setState({ selectedRowKeys });
  };

  // 新增
  add = () => {
    this.setState(
      {
        addvisibe: true,
        modalScore: 'add',
        tid: '',
        tempKeywords: [],
      },
      () => {
        this.props.form.setFieldsValue({
          tempChannel: null,
          tempUrl: null,
          tempKeywords: [],
          tempTitle: null,
          tempStatus: 1,
          tempTime: null,
          tempBehavior: null,
          tempId: null,
        });
      },
    );
  };
  // modal的确认，确认添加和确认更新的
  addOk = () => {
    this.props.form.validateFields({ force: true }, (err, value) => {
      if (!err) {
        if (this.state.modalScore === 'add') {
          // 调用添加的
          this.props.dispatch({
            type: 'messageIndex/addList',
            payload: {
              channelId: value.tempChannel,
              // "id": value.tempId,
              jumpUrl: value.tempUrl,
              keywordList: this.state.tempKeywords,
              title: value.tempTitle,
              status: value.tempStatus,
              triggerInterval: value.tempTime,
              userBehavior: value.tempBehavior,
              userTemplateId: value.tempId,
            },
            callback: res => {
              if (res.responseType === 'SUCCESS') {
                message.success(res.data.data);
                this.setState(
                  {
                    addvisibe: false,
                  },
                  () => {
                    this.getList();
                  },
                );
              } else {
                message.error(res.data.msg);
              }
            },
          });
        } else {
          // 调用编辑的
          this.props.dispatch({
            type: 'messageIndex/updateList',
            payload: {
              id: this.state.tid,
              channelId: value.tempChannel,
              jumpUrl: value.tempUrl,
              keywordList: this.state.tempKeywords,
              title: value.tempTitle,
              status: value.tempStatus,
              triggerInterval: value.tempTime,
              userBehavior: value.tempBehavior,
              userTemplateId: value.tempId,
            },
            callback: res => {
              if (res.responseType === 'SUCCESS') {
                message.success('编辑成功');
                this.setState(
                  {
                    addvisibe: false,
                  },
                  () => {
                    // this.props.form.resetFields();
                    this.getList();
                  },
                );
              } else {
                message.error('编辑失败：' + res.data.msg);
              }
            },
          });
        }
      }
    });
  };
  tempKeywordsValidator = (rule, val, callback) => {
    val = this.state.tempKeywords;
    if (!(val && val.length)) {
      callback('模板关键词不能为空');
    }
    let validateResult = true;
    val.forEach(item => {
      if (!(item.keyword && item.value)) {
        validateResult = false;
      }
    });
    if (!validateResult) {
      callback('模板关键词不能有空格');
    }
    callback();
  };
  tempTimeValidator = (rule, val, callback) => {
    if (/^[0-6]$/.test(val)) {
      callback();
    } else {
      callback('只能输入0-6的数字');
    }
  };
  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      this.setState(
        {
          loading: true,
        },
        () => {
          this.props.dispatch({
            type: 'messageIndex/getList',
            payload: {
              pageNumber: 1,
              pageSize: 10,
              title: values.title1,
              channelId: values.tempChannel1,
            },
            callback: res => {
              console.log(res);
              if (res.responseType === 'SUCCESS') {
                message.success('获取信息成功');
                this.setState({
                  total: res.data.total,
                  current: res.data.current,
                  loading: false,
                });
              } else {
                message.error(res.msg);
              }
            },
          });
        },
      );
    });
  };
  
  handleReset = e => {
    this.props.form.resetFields();
    this.props.form.setFieldsValue({
      status: undefined,
      type: undefined,
    });
    this.handleSubmit(e);
  };
  
  render() {
    const {
      total,
      current,
      addvisibe,
      modalScore,
      channelData,
      tempBehavior,
      tempId,
      tempTitle,
      tempStatus,
      tempKeywords,
      tempUrl,
      tempTime,
      tempChannel,
    } = this.state;
    const paginationProps = {
      current: current,
      pageSize: 10,
      total: total,
      showTotal: total => (
        <span style={{ fontSize: '14px' }}>
          <span>共{Math.ceil(total / 10)}页</span>&emsp;
          <span>共{total}条</span>
        </span>
      ),
    };
    const { list } = this.props;
    const editColumns = [
      {
        title: '关键词',
        dataIndex: 'keyword',
        editable: true,
        width: '40%',
        render: (text, record, index) => (
          <Input
            defaultValue={text}
            onPressEnter={e => this.save(e, index, 'keyword')}
            onBlur={e => this.save(e, index, 'keyword')}
          />
        ),
      },
      {
        title: '内容',
        dataIndex: 'value',
        editable: true,
        width: '40%',
        render: (text, record, index) => (
          <Input
            defaultValue={text}
            onPressEnter={e => this.save(e, index, 'value')}
            onBlur={e => this.save(e, index, 'value')}
          />
        ),
      },
      {
        title: (
          <Icon
            onClick={() => this.addTempKeyword()}
            style={{ cursor: 'pointer' }}
            type="plus-circle"
          />
        ),
        dataIndex: 'operation',
        align: 'center',
        width: '20%',
        render: (text, record, index) => {
          return (
            <Icon
              onClick={() => this.deleteTempKeyword(index)}
              style={{ cursor: 'pointer' }}
              type="minus-circle"
            />
          );
        },
      },
    ];

    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };
    return (
      <PageHeaderWrapper>
        <Card bordered={false}>
          <Form layout="inline" onSubmit={this.handleSubmit}>
            <Form.Item label={'模版标题'}>
              {getFieldDecorator('title1', {})(<Input placeholder="请输入模版标题" />)}
            </Form.Item>
            <Form.Item label={'发送渠道'}>
              {getFieldDecorator('tempChannel1')(
                <Select style={{ width: '160px' }} placeholder="请选择发送渠道">
                  <Option value="">全部</Option>
                  {channelData.map((item, sign) => {
                    return (
                      <Option key={item.channelId} value={item.channelId}>
                        {item.channelName}
                      </Option>
                    );
                  })}
                </Select>,
              )}
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </Form.Item>
            <Form.Item>
              <Button htmlType="button" onClick={this.handleReset}>
                重置
              </Button>
            </Form.Item>
          </Form>
          <Button
            type="primary"
            onClick={this.add}
            style={{
              margin: '20px 0',
            }}
          >
            新增
          </Button>
          {/* <Table
            columns={this.columns}
            // loading={loading}
            tableLayout="fixed"
            size="small"
            dataSource={onTableData([{}])}
            pagination={{
              current: current,
              total: total,
              onChange: this.onChange,
              showTotal: this.showTotal,
              showQuickJumper: true,
              pageSizeOptions: ['5', '10', '20'],
              showSizeChanger: true,
              onShowSizeChange: this.onShowSizeChange,
            }}
          /> */}

          <MyPageTable
            paginationProps={paginationProps}
            dataSource={onTableData(list)}
            columns={this.columns}
            onPage={this.onChange}
          />
        </Card>
        <Modal
          title={modalScore == 'add' ? '新增' : '修改'}
          visible={addvisibe}
          onCancel={() => {
            this.setState({
              addvisibe: false,
            });
            this.props.form.resetFields();
          }}
          onOk={this.addOk}
        >
          <Form {...formItemLayout}>
            <Form.Item label="用户行为">
              {getFieldDecorator('tempBehavior', {
                rules: [
                  {
                    required: true,
                    message: '用户行为不能为空',
                  },
                ],
                initialValue: tempBehavior ? tempBehavior : null,
              })(
                <Select placeholder="请选择发送渠道">
                  <Option value="AUTHORIZED_LOGIN">授权登陆后但是未成功下单</Option>
                  <Option value="LEASE">点击立即租赁但未成功下单</Option>
                  <Option value="COLLECTION">收藏成功后未成功下单</Option>
                </Select>,
              )}
            </Form.Item>
            <Form.Item label="模板id">
              {getFieldDecorator('tempId', {
                rules: [
                  {
                    required: true,
                    message: '模板id不能为空',
                  },
                ],
                initialValue: tempId ? tempId : null,
              })(<Input disabled={modalScore === 'edit'} />)}
            </Form.Item>
            <Form.Item label="模板标题">
              {getFieldDecorator('tempTitle', {
                rules: [
                  {
                    required: true,
                    message: '模板标题不能为空',
                  },
                ],
                initialValue: tempTitle ? tempTitle : null,
              })(<Input />)}
            </Form.Item>
            <Form.Item label="是否生效">
              {getFieldDecorator('tempStatus', {
                rules: [
                  {
                    required: true,
                    message: '模板状态不能为空',
                  },
                ],
                initialValue: tempStatus ? tempStatus : null,
              })(
                <Select style={{ width: '100%' }} placeholder="请选择模板状态">
                  <Option key={1} value={1}>
                    生效
                  </Option>
                  <Option key={0} value={0}>
                    不生效
                  </Option>
                </Select>,
              )}
            </Form.Item>
            <Form.Item label="模板关键词">
              {getFieldDecorator('tempKeywords', {
                rules: [
                  {
                    required: true,
                    validator: this.tempKeywordsValidator,
                  },
                ],
                initialValue: tempKeywords ? tempKeywords : [],
              })(
                <Table
                  bordered
                  size="small"
                  dataSource={tempKeywords}
                  rowKey={record => record.keyword + Math.random()}
                  columns={editColumns}
                  pagination={false}
                />,
              )}
            </Form.Item>
            <Form.Item label="跳转页面">
              {getFieldDecorator('tempUrl', {
                rules: [
                  {
                    required: true,
                    message: '跳转页面不能为空',
                  },
                ],
                initialValue: tempUrl ? tempUrl : null,
              })(<Input />)}
            </Form.Item>
            <Form.Item label="发送时间间隔">
              {getFieldDecorator('tempTime', {
                rules: [
                  {
                    required: true,
                    message: '发送时间间隔不能为空',
                  },
                  // {
                  //   validator: this.tempTimeValidator,
                  // },
                ],
                initialValue: tempTime ? tempTime : null,
              })(<Input addonAfter="分钟" />)}
            </Form.Item>
            <Form.Item label="发送渠道">
              {getFieldDecorator('tempChannel', {
                rules: [
                  {
                    required: true,
                    message: '发送渠道不能为空',
                  },
                ],
                initialValue: tempChannel ? tempChannel : '',
              })(
                <Select
                  // mode="multiple"
                  style={{ width: '100%' }}
                  placeholder="请选择发送渠道"
                  disabled={modalScore === 'edit'}
                >
                  {channelData.map((item, sign) => {
                    return (
                      <Option key={item.channelId} value={item.channelId}>
                        {item.channelName}
                      </Option>
                    );
                  })}
                </Select>,
              )}
            </Form.Item>
          </Form>
        </Modal>
      </PageHeaderWrapper>
    );
  }
}

export default MessageSetting;
